<?php
namespace app\admin\controller\member;
use app\admin\command\Api\library\Extractor;
use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use think\Controller;
use think\Request;
use think\facade\Lang;
use fast\Random;
use fast\Tree;
use fast\Cols;
use fast\Date;
use think\cache\Driver\File;
class Membergroup extends Backend{
		protected $model = null;//模型对象
		protected $columnlist = array();
		public function initialize(){
				parent::initialize();
				$this->model = model('MemberGroup');
				$this->columnarry = Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/module.php','',1);
		}
		public function listforajax(){
				$lst = $this->model->order('itemid','desc')->select();
				print_r(json_encode($lst));
				exit;
		}
		public function add(){
				if ($this->request->isPost()){
						$params = $this->request->post("row/a");
						if ($params){
								$fc = new File();
								$this->modelValidate = false;
								if ($this->dataLimit){
										$params[$this->dataLimitField] = $this->auth->id;
								}
								try{
										//是否采用模型验证
										if ($this->modelValidate){
												$name = basename(str_replace('\\', '/', get_class($this->model)));
												$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
												$this->model->validate($validate);
										}
										$params['itemid'] = str_replace('-','',Random::uuid());
										$result = $this->model->allowField(true)->save($params);
										if ($result !== false){
												$this->success();
										}else{
												$this->error($this->model->getError());
										}
								}
								catch (\think\exception\PDOException $e){
										$this->error($e->getMessage());
								}
						}
						$this->error(__('Parameter %s can not be empty', ''));
				}else{
						$fc = new File();
						return $this->view->fetch();
				}
		}
		public function edit($ids = NULL){
				$row = $this->model->get($ids);$fc = new File();

				$id = $ids;
				if (!$row){$this->error(__('No Results were found'));}
				// $adminIds = $this->getDataLimitAdminIds();
				// if (is_array($adminIds)){
				// 		if (!in_array($row[$this->dataLimitField], $adminIds)){
				// 				$this->error(__('You have no permission'));
				// 		}
				// }
				if ($this->request->isPost()){
						$params = $this->request->post("row/a");
						if ($params){
								try{
										//是否采用模型验证
										if ($this->modelValidate){
												$name = basename(str_replace('\\', '/', get_class($this->model)));
												$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
												$row->validate($validate);
										}
										$result = $row->allowField(true)->save($params);
										if ($result !== false){$this->success();}
										else{$this->error($row->getError());}
								}
								catch (\think\exception\PDOException $e){
										$this->error($e->getMessage());
								}
						}
						$this->error(__('Parameter %s can not be empty', ''));
				}
				//print_r($ids);exit;
				$this->view->assign("ids",$id);
				$this->view->assign("row", $row);
				return $this->view->fetch();
		}
		public function index(){
				$columnlist = Cols::columnread('membergroup');
				$flag = array();$options = array();
				foreach($columnlist as $v){
						$flag[] = $v['listorder'];
						if($v['options']){
								//把带有选项的列，提取出来。
								$options[$v['columnenname']] = $v['options'];
						}
				}
				array_multisort($flag, SORT_ASC, $columnlist);
				//设置过滤方法
				$this->request->filter(['strip_tags']);
				//如果发送的来源是Selectpage，则转发到Selectpage
				if ($this->request->request('pkey_name')){
						return $this->selectpage();
				}
				$searchfileds = array();
				$searchfileds['name'] = 'varcharshort';
				list($where, $sort, $order, $offset, $limit) = $this->buildparams($searchfileds);
				$order = 'desc';
				$sort = 'itemid';
				$total = $this->model
				->where($where)
				->order($sort, $order)
				->count();
				$totalpage = 1;$page = 1;
				if($limit>0){
						$totalpage = $total%$limit==0?intval($total/$limit):intval($total/$limit)+1;
						//总页数
						if($offset>0){$page = intval($offset/$limit)+1;}
				}
				$list = $this->model
				->where($where)
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
				for ($i = 0; $i < count($list); $i++) {
						if(isset($list[$i]['category'])){
								$list[$i]['catname'] = $list[$i]['category']['name'];
						}
						unset($list[$i]['intro']);unset($list[$i]['content']);
						foreach ($options as $k => $v) {
								if(isset($list[$i][$k])){
										$arj = json_decode($v,true);
										$sarj = $arj[$list[$i][$k]];
										$list[$i][$k] = $sarj;
								}
						}
						//$list[$i]['createtime'] = Date::timetodate($list[$i]['createtime'],3);
				}
				$result = array("total" => $total, "rows" => $list);
				$this->view->assign("lists",$result['rows']);
				$this->view->assign("listsjson",json_encode($result['rows']));
				$this->view->assign("columnlistjson",json_encode($columnlist));
				$this->view->assign("columnlist",$columnlist);
				$this->view->assign("total",$result['total']);
				$this->view->assign("offset",$offset);
				$this->view->assign("limit",$limit);
				$this->view->assign("totalpage",$totalpage);
				$this->view->assign("page",$page);
				return $this->view->fetch('index');
		}
		public function showlist(){
				$ids = $this->request->post('ids');
				$ischeck = $this->request->post('ischeck');
				model('Column')->where('itemid',$ids)->update(['isshowlist'=>($ischeck==='true'?1:0)]);
				$ll = model('Column')->getColumnsByModel('membergroup');
				$lls = array();
				foreach ($ll as $k => $v) {
						$lls[ucfirst($v['columnenname'])] = $v;
				}
				$string = "<?php return ".var_export($lls, true)."; ?>";
				$filename = COLUMN_PATH.DS.'membergroup.php';
				$result = file_put_contents($filename, $string);
				if(@$fp = fopen($filename,'wb')) {
						flock($fp, LOCK_EX);
						$len = fwrite($fp, $string);
						flock($fp, LOCK_UN);
						fclose($fp);
						echo $len;exit;
				} else {
						echo '失败了';exit;
				}
		}

		/**
		* 读取角色权限树
		*
		* @internal
		*/
		public function roletree(){
			$this->loadlang('member/group');
			$model = model('MemberGroup');
			$id = $this->request->post("id");
			$pid = $this->request->post("pid");
			$parentGroupModel = $model->get($pid);
			$currentGroupModel = NULL;
			if ($id){
				$currentGroupModel = $model->get($id);
			}
			$id = $id ? $id : NULL;
			$ruleList = collection(model('MemberRule')->order('weigh', 'desc')->select())->toArray();
			/*
			//读取父类角色所有节点列表
			$parentRuleList = [];
			if (in_array('*', explode(',', $parentGroupModel->rules))){
					$parentRuleList = $ruleList;
			}else{
					$parentRuleIds = explode(',', $parentGroupModel->rules);
					foreach ($ruleList as $k => $v)
					{
							if (in_array($v['itemid'], $parentRuleIds))
							{
									$parentRuleList[] = $v;
							}
					}
			}
			*/
			//当前所有正常规则列表
			Tree::instance()->init($ruleList);
			//读取当前角色下规则ID集合
			//$adminRuleIds = $this->auth->getRuleIds();
			//是否是超级管理员
			//$superadmin = $this->auth->isSuperAdmin();
			//当前拥有的规则ID集合
			$currentRuleIds = $id ? explode(',', $currentGroupModel->rules) : $ruleList;
			$parentRuleList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(''), 'name');
			$parentRuleIds = array_map(function($item) {
					return $item['itemid'];
			}, $parentRuleList);
			$nodeList = [];
			foreach ($parentRuleList as $k => $v){
				// if (!$superadmin && !in_array($v['itemid'], $adminRuleIds))
					// 	 continue;
				// if ($v['pid'] && !in_array($v['pid'], $parentRuleIds))
					// 	 continue;
				$state = array('selected' => in_array($v['itemid'], $currentRuleIds));
				$nodeList[] = array('id' => $v['itemid'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => __($v['name']), 'type' => 'menu', 'state' => $state);
			}
			$this->success('', null, $nodeList);
					/*
					if (!$id || !in_array($pid, Tree::instance()->getChildrenIds($id, TRUE)))
					{
							$parentRuleList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(''), 'name');
							$hasChildrens = [];
							foreach ($parentRuleList as $k => $v)
							{
									if ($v['haschild'])
											$hasChildrens[] = $v['itemid'];
							}
							$parentRuleIds = array_map(function($item) {
									return $item['itemid'];
							}, $parentRuleList);
							$nodeList = [];
							foreach ($parentRuleList as $k => $v)
							{
									// if (!$superadmin && !in_array($v['itemid'], $adminRuleIds))
										// 	 continue;
									if ($v['pid'] && !in_array($v['pid'], $parentRuleIds))
											continue;
									$state = array('selected' => in_array($v['itemid'], $currentRuleIds) && !in_array($v['itemid'], $hasChildrens));
									$nodeList[] = array('id' => $v['itemid'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => __($v['title']), 'type' => 'menu', 'state' => $state);
							}
							$this->success('', null, $nodeList);
					}
					else{
							$this->error(__('Can not change the parent to child'));
					}

					if (($pid || $parentGroupModel) && (!$id || $currentGroupModel))
					{

					}
					else
					{
						$this->error(__('Group not found'));
					}
					*/
		}

		/**
		* 读取角色的接口权限树
		*
		* @return 返回控制器函数的描述
		*/
		public function roleinterface(){
			$this->loadlang('member/group');
			$model = model('MemberGroup');
			$id = $this->request->post("id");
			$pid = $this->request->post("pid");
			$parentGroupModel = $model->get($pid);
			$currentGroupModel = NULL;
			if ($id){
				$currentGroupModel = $model->get($id);
			}
			$id = $id ? $id : NULL;
			$ruleList = collection(model('MemberRule')->order('weigh', 'desc')->select())->toArray();
						
			//$moduleDir = ROOT_PATH . 'application' . DS .'index' . DS . 'controller' . DS;
			$moduleDir = ROOT_PATH . 'application' . DS;
			if (!is_dir($moduleDir)) {
				throw new Exception('module not found');
			}
			if (version_compare(PHP_VERSION, '7.0.0', '<')) {
				if (extension_loaded('Zend OPcache')) {
					$configuration = opcache_get_configuration();
					$directives = $configuration['directives'];
					$configName = request()->isCli() ? 'opcache.enable_cli' : 'opcache.enable';
					if (!$directives[$configName]) {
						throw new Exception("Please make sure {$configName} is turned on, Get help:https://forum.fastadmin.net/d/1321");
					}
				} else {
					throw new Exception("Please make sure opcache already enabled, Get help:https://forum.fastadmin.net/d/1321");
				}
			}
			$pathes = new \RecursiveDirectoryIterator($moduleDir);
			$delarray = config('noneedright.');
			foreach ($pathes as $name => $file1) {
				$fname = $file1->getFileName();
				if(in_array($fname,$delarray['brightdirarr'])){
					$moduleDir = ROOT_PATH . 'application' . DS . $fname . DS . 'controller' . DS;
					$files = new \RecursiveIteratorIterator(
						new \RecursiveDirectoryIterator($moduleDir), \RecursiveIteratorIterator::LEAVES_ONLY
					);
					foreach ($files as $name => $file) {
						if (!$file->isDir()) {
							$filePath = $file->getRealPath();							
							$filename = $file->getFileName();//获取文件名
							if(in_array($filename, $delarray['brightarr'])){
								continue;
							}
							$contents = file_get_contents($filePath);
							$namespace = $class = "";
							$getting_namespace = false;$getting_class = false;
							foreach (token_get_all($contents) as $token) {
								//If this token is the namespace declaring, then flag that the next tokens will be the namespace name
								if (is_array($token) && $token[0] == T_NAMESPACE) {
									$getting_namespace = true;
								}
								//If this token is the class declaring, then flag that the next tokens will be the class name
								if (is_array($token) && $token[0] == T_CLASS) {
									$getting_class = true;
								}
								//While we're grabbing the namespace name...
								if ($getting_namespace === true) {
									//If the token is a string or the namespace separator...
									if (is_array($token) && in_array($token[0], [T_STRING, T_NS_SEPARATOR])) {
										//Append the token's value to the name of the namespace
										$namespace .= $token[1];
									} else if ($token === ';') {
										//If the token is the semicolon, then we're done with the namespace declaration
										$getting_namespace = false;
									}
								}
								//While we're grabbing the class name...
								if ($getting_class === true) {
									//If the token is a string, it's the name of the class
									if (is_array($token) && $token[0] == T_STRING) {
										//Store the token's value as the class name
										$class = $token[1];
										//Got what we need, stope here
										break;
									}
								}
							}
							$classes[] = $namespace ? $namespace . '\\' . $class : $class;
						}
					}
				}
			}	
			$output = array();
			$c = 0;
			foreach ($classes as $class){
				//获取了控制器函数的注释
				$output = Extractor::getAllClassAnnotations($class);
			}
			$parentRuleList = array();

			foreach ($output as $k => $v) {
				$arr = explode('\\',$k);
				$ary = array();
				$ary['itemid'] = $arr[0];
				$ary['pid'] = '';
				$ary['name'] = $arr[0]; 
				$ary['title'] = $arr[0];
				$ary['icon'] = 'fa fa-circle-o';
				$ary['weight'] = 0;
				$parentRuleList[] = $ary;
				//添加第一个
				if(isset($arr[1])){
					$ary['itemid'] = $arr[1];
					$ary['pid'] = $arr[0];
					$ary['name'] = $arr[1]; 
					$ary['title'] = $arr[1];
					$ary['icon'] = 'fa fa-circle-o';
					$ary['weight'] = 1;
					$parentRuleList[] = $ary;
				}
				foreach ($v as $kk => $vv) {
					$ary = array();
					$ary['pid'] = isset($arr[1])?$arr[1]:$arr[0];
					$ary['icon'] = 'fa fa-circle-o';
					$ary['weight'] = 2;
					foreach ($vv as $kkk => $val) {
						switch($kkk){
							case 'ApiRoute':
								$ary['itemid'] = $vv['ApiRoute'][0];
								$ary['name'] = $vv['ApiRoute'][0];
							break;
							case 'ApiTitle':
								$ary['title'] = $vv['ApiTitle'][0].'|'.$kk;
							break;
						}
					}
					$parentRuleList[] = $ary;
				}
			}
			
			//当前所有正常规则列表
			Tree::instance()->init($parentRuleList);
			//读取当前角色下规则ID集合
			$adminRuleIds = $this->auth->getInterfaceIds();
			//是否是超级管理员
			$superadmin = $this->auth->isSuperAdmin();
			//当前拥有的规则ID集合
			$currentRuleIds = $id ? explode(',', $currentGroupModel->interfaces) : [];

			if (!$id || !in_array($pid, Tree::instance()->getChildrenIds($id, TRUE))){
				$parentRuleList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(''), 'name');
				$hasChildrens = [];
				foreach ($parentRuleList as $k => $v){
					if ($v['haschild'])
						$hasChildrens[] = $v['itemid'];
				}
				$parentRuleIds = array_map(function($item) {
					return $item['itemid'];
				}, $parentRuleList);
				$nodeList = [];
				foreach ($parentRuleList as $k => $v){
					if (!$superadmin && !in_array($v['itemid'], $adminRuleIds))
						continue;
					if ($v['pid'] && !in_array($v['pid'], $parentRuleIds))
						continue;
					$state = array('selected' => in_array($v['itemid'], $currentRuleIds) && !in_array($v['itemid'], $hasChildrens));
					$nodeList[] = array('id' => $v['itemid'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => __($v['title']), 'type' => 'menu', 'state' => $state);
				}
				$this->success('', null, $nodeList);
			}else{
				$this->error(__('Can not change the parent to child'));
			}
			/*
			if (($pid || $parentGroupModel) && (!$id || $currentGroupModel)){
				$id = $id ? $id : NULL;
				$ruleList = collection(model('MemberRule')->order('weigh', 'desc')->select())->toArray();
							
				$moduleDir = ROOT_PATH . 'application' . DS .'admin' . DS . 'controller' . DS;
				if (!is_dir($moduleDir)) {
					throw new Exception('module not found');
				}
				if (version_compare(PHP_VERSION, '7.0.0', '<')) {
					if (extension_loaded('Zend OPcache')) {
						$configuration = opcache_get_configuration();
						$directives = $configuration['directives'];
						$configName = request()->isCli() ? 'opcache.enable_cli' : 'opcache.enable';
						if (!$directives[$configName]) {
							throw new Exception("Please make sure {$configName} is turned on, Get help:https://forum.fastadmin.net/d/1321");
						}
					} else {
						throw new Exception("Please make sure opcache already enabled, Get help:https://forum.fastadmin.net/d/1321");
					}
				}
				
				$files = new \RecursiveIteratorIterator(
					new \RecursiveDirectoryIterator($moduleDir), \RecursiveIteratorIterator::LEAVES_ONLY
				);
				$delarray = config('noneedright.');
				
				foreach ($files as $name => $file) {
					if (!$file->isDir()) {
						$filePath = $file->getRealPath();
						$filename = $file->getFileName();//获取文件名
						if(in_array($filename, $delarray['rightarr'])){
							continue;
						}
						$contents = file_get_contents($filePath);
						$namespace = $class = "";
						$getting_namespace = false;$getting_class = false;
						foreach (token_get_all($contents) as $token) {
							//If this token is the namespace declaring, then flag that the next tokens will be the namespace name
							if (is_array($token) && $token[0] == T_NAMESPACE) {
								$getting_namespace = true;
							}
							//If this token is the class declaring, then flag that the next tokens will be the class name
							if (is_array($token) && $token[0] == T_CLASS) {
								$getting_class = true;
							}
							//While we're grabbing the namespace name...
							if ($getting_namespace === true) {
								//If the token is a string or the namespace separator...
								if (is_array($token) && in_array($token[0], [T_STRING, T_NS_SEPARATOR])) {
									//Append the token's value to the name of the namespace
									$namespace .= $token[1];
								} else if ($token === ';') {
									//If the token is the semicolon, then we're done with the namespace declaration
									$getting_namespace = false;
								}
							}
							//While we're grabbing the class name...
							if ($getting_class === true) {
								//If the token is a string, it's the name of the class
								if (is_array($token) && $token[0] == T_STRING) {
									//Store the token's value as the class name
									$class = $token[1];
									//Got what we need, stope here
									break;
								}
							}
						}
						$classes[] = $namespace ? $namespace . '\\' . $class : $class;
					}
				}
				$output = array();
				$c = 0;
				foreach ($classes as $class){
					//获取了控制器函数的注释
					$output = Extractor::getAllClassAnnotations($class);
				}
				$parentRuleList = array();

				foreach ($output as $k => $v) {
					$arr = explode('\\',$k);
					$ary = array();
					$ary['itemid'] = $arr[0];
					$ary['pid'] = '';
					$ary['name'] = $arr[0]; 
					$ary['title'] = $arr[0];
					$ary['icon'] = 'fa fa-circle-o';
					$ary['weight'] = 0;
					$parentRuleList[] = $ary;
					//添加第一个
					if(isset($arr[1])){
						$ary['itemid'] = $arr[1];
						$ary['pid'] = $arr[0];
						$ary['name'] = $arr[1]; 
						$ary['title'] = $arr[1];
						$ary['icon'] = 'fa fa-circle-o';
						$ary['weight'] = 1;
						$parentRuleList[] = $ary;
					}
					foreach ($v as $kk => $vv) {
						$ary = array();
						$ary['pid'] = isset($arr[1])?$arr[1]:$arr[0];
						$ary['icon'] = 'fa fa-circle-o';
						$ary['weight'] = 2;
						foreach ($vv as $kkk => $val) {
							switch($kkk){
								case 'ApiRoute':
									$ary['itemid'] = $vv['ApiRoute'][0];
									$ary['name'] = $vv['ApiRoute'][0];
								break;
								case 'ApiTitle':
									$ary['title'] = $vv['ApiTitle'][0].'|'.$kk;
								break;
							}
						}
						$parentRuleList[] = $ary;
					}
				}
				
				//当前所有正常规则列表
				Tree::instance()->init($parentRuleList);
				//读取当前角色下规则ID集合
				$adminRuleIds = $this->auth->getInterfaceIds();
				//是否是超级管理员
				$superadmin = $this->auth->isSuperAdmin();
				//当前拥有的规则ID集合
				$currentRuleIds = $id ? explode(',', $currentGroupModel->interfaces) : [];

				if (!$id || !in_array($pid, Tree::instance()->getChildrenIds($id, TRUE))){
					$parentRuleList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(''), 'name');
					$hasChildrens = [];
					foreach ($parentRuleList as $k => $v){
						if ($v['haschild'])
							$hasChildrens[] = $v['itemid'];
					}
					$parentRuleIds = array_map(function($item) {
						return $item['itemid'];
					}, $parentRuleList);
					$nodeList = [];
					foreach ($parentRuleList as $k => $v){
						if (!$superadmin && !in_array($v['itemid'], $adminRuleIds))
							continue;
						if ($v['pid'] && !in_array($v['pid'], $parentRuleIds))
							continue;
						$state = array('selected' => in_array($v['itemid'], $currentRuleIds) && !in_array($v['itemid'], $hasChildrens));
						$nodeList[] = array('id' => $v['itemid'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => __($v['title']), 'type' => 'menu', 'state' => $state);
					}
					$this->success('', null, $nodeList);
				}else{
					$this->error(__('Can not change the parent to child'));
				}	
			}else{
				$this->error(__('Group not found'));
			}
			*/
		}
}?>
